package com.nms.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;

import com.nms.dao.TakeDao;
import com.nms.model.Email;
import com.nms.model.TakeUser;
import com.nms.model.Type;

@Component("takeDao")
public class TakeDaoImpl implements TakeDao {
	private HibernateTemplate hibernateTemplate;

	@SuppressWarnings("unchecked")
	@Override
	public List<Type> findAllGroup() {
		List<Type> list = hibernateTemplate.find("from Type");
		return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<TakeUser> getUserByType(String typename) {
		List<TakeUser> tUsers = hibernateTemplate
				.find("from TakeUser where typename = '" + typename + "'");
		return tUsers;
	}

	@Override
	public boolean take(Type type, String username) {
		TakeUser tu = new TakeUser();
		tu.setType(type.getType());
		tu.setTypename(type.getTypename());
		tu.setUsername(username);
		boolean flag = false;
		try {
			hibernateTemplate.save(tu);
			flag = true;
		} catch (Exception ex) {
			flag = false;
		}
		return flag;
	}

	@Override
	public boolean cancel(int type, String username) {
		boolean flag = false;
		try {
			Session session = hibernateTemplate.getSessionFactory()
					.openSession();
			String hql ="delete from TakeUser tu where tu.type = " + type
					+ "and tu.username = '" + username + "'";
			Query q = session.createQuery(hql);
			q.executeUpdate();
			flag = true;
		} catch (Exception ex) {
			flag = false;
		}
		return flag;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Email> findUTake(String username) {
		List<Email> list = hibernateTemplate
				.find("from Email where tousername = '" + username + "'"
						+ "and type = 1");
		return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Type> getUNotTakeList(String username) {
		List<TakeUser> uTakeList = getUTakeList(username);
		String temp = "";
		for (int i = 0; i < uTakeList.size(); i++) {
			TakeUser takeUser = uTakeList.get(i);
			if (i == 0) {
				temp = "type !=" + takeUser.getType();
			} else {
				temp = temp+ " and type !=" + takeUser.getType();
			}
		}
		if (!temp.equals("")) {
			List<Type> list = hibernateTemplate.find("from Type where " + temp);
			return list;
		}
		else
		{
			List<Type> list = hibernateTemplate.find("from Type");
			return list;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<TakeUser> getUTakeList(String username) {
		List<TakeUser> list = hibernateTemplate
				.find("from TakeUser where username = '" + username + "'");
		return list;
	}

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

}
